import { requestSDspotMarketZcq } from "@src/api/fetch"
import { promisetTimeOut } from "@src/utils/common"
import { CaptchaParams, CaptchaResult, PicData } from "./type"
import { priviateAccount, pyApiBaseUrl, userUnitid } from "@src/config/accountInfo"

/** 获取交易中心的验证码的图片数据 */
const getPic = async ({headers}:{headers:HeadersInit}) => {
  try {
    const formParams = new URLSearchParams({
      jytype: 'lxch'
    })
    const dataObj:PicData = await requestSDspotMarketZcq(
      'https://pmos.sd.sgcc.com.cn:18080/zcq/ImageVerification.do?method=getPic',
      formParams,
      { method:'POST', headers }
    )

    return Promise.resolve(dataObj)
  }catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** python 解析验证码 接口*/
const myCheckcapcode = async (images:PicData)=> {
  try {
    const res = await requestSDspotMarketZcq(
      `${pyApiBaseUrl}/captchaSolver`,
      JSON.stringify(images),
      { method:'POST', headers:{'Content-Type':'application/json'} }
    )
    console.log('myCheckcapcode', res)
    return Promise.resolve({xpos: res?.target?.[0] || 0, capcode: images.capcode, unitid:''})
  } catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** 交易中心的验证接口，获取验证结果 */
const checkcapcode = async ({headers, captcha}:{headers:HeadersInit, captcha:CaptchaParams}) => {
  try {
    const {xpos,capcode} = captcha
    const formParams = new URLSearchParams({
      xpos: String(xpos),
      capcode: String(capcode),
      unitid: userUnitid[priviateAccount]
    })
    const dataObj:CaptchaResult = await requestSDspotMarketZcq(
      'https://pmos.sd.sgcc.com.cn:18080/zcq/ImageVerification.do?method=checkcapcode',
      formParams,
      { method:'POST', headers }
    )
    return Promise.resolve(dataObj)
  }catch(e) {
    console.error(e)
    return Promise.reject(e)
  }
}

/** 记录验证失败的递归次数 */
let getDayRollCaptchaTimesLimit = 0

/** 获取验证结果，用于下单 */
export const getDayRollCaptchaResult = async ({headers, delay = 2500}:{headers:HeadersInit,delay:number}) => {
  try{
    const images:PicData = await getPic({headers})
  //   const images = {
  //     "capcode": "1730959107583qysf4536",
  //     "slidingImage":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phooq0c0gzRmiigQoNWI6KKUi4bkvajPNFFQdUR4NSqaKKTN4kynNKTRRUmiGk03dRRQDDdSZoopksM0hNFFBLEzSZoopkhmkoopiP/Z",
  //     "yHeight": 60
  // }
    if(!images || !images.capcode) {
      console.error('获取验证码失败！')
      return Promise.resolve({code:3,val:''})
    }

    const myCheckRes = await myCheckcapcode(images)
    await promisetTimeOut(delay) // 延时 防反爬
    let checkRes:CaptchaResult = await checkcapcode({headers, captcha: myCheckRes})

    if(checkRes?.code !== 1 || !checkRes?.val) {
      if(getDayRollCaptchaTimesLimit >= 3) {
        console.error('获取日滚动撮合验证结果失败！')
        return Promise.resolve({code:3,val:''})
      }
        
      ++getDayRollCaptchaTimesLimit
      checkRes = await getDayRollCaptchaResult({headers, delay})
    }

    return Promise.resolve(checkRes)
  }catch(e) {
    console.error(e)
    return Promise.resolve({code:3, val:''})
  }finally {
    getDayRollCaptchaTimesLimit = 0
  }
}
